/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * Copyright 2009 Synergy Energy Holdings, LLC. All rights reserved.
 * 
 * EmailConstraintValidator.java
 * @date: Mar 5, 2009
 * @author mlee
 */
package experimental.com.rhythm.commons.validation.bean;

import experimental.com.rhythm.commons.validation.bean.annotation.Length;

/**
 *
 * @author mlee
 */
public class LengthConstraintValidator extends ConstraintValidator<Length> {

    private String message;

    private int min;

    private int max;

    @Override
    public void initialize(Length constraint) {
        this.min = constraint.min();
        this.max = constraint.max();
        this.message = constraint.message();
    }

    @Override
    public void checkConstraint(Object value) {
        failIfNull(value);
        checkStringLength(value);
    }

    private void checkStringLength(Object value) {
        if (isString(value)) {
            final String stringValue = value.toString();
            if (stringValue.length() > max || stringValue.length() < min) {
                fail(message);
            }
        }
    }

    private void failIfNull(Object value) {
        if (isNull(value)) {
            fail(message);
        }
    }
}
